package com.ndf.learn.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by lin on 4/8/18.
 */
@Component
@Aspect
@Order(1)
public class CryptoAdvice {

    @Pointcut("execution(@com.ndf.learn.aop.CryptoTag * com.ndf.learn.controller.*Controller.*(..))")
    public void cryptoJoinPoint(){}

    @Around("cryptoJoinPoint()")
    public Object handleCrypto(ProceedingJoinPoint point){
        Class<?> clazz = point.getTarget().getClass();
        String className = clazz.getName();
        Method method = ((MethodSignature)point.getSignature()).getMethod();
        String methodName = method.getName();

        RequestMapping reqMap = method.getAnnotation(RequestMapping.class);
        String[] urlArr = reqMap.value();

        System.out.println("==========" + urlArr[0]);

        Object result = null;
        try {
            //前置通知
            System.out.println("The method "+ methodName+" start. param<"+ Arrays.asList(point.getArgs())+">");

            //执行目标方法
            result = point.proceed();

            //返回通知
            System.out.println("The method "+ methodName+" end. result<"+ result+">");

            //处理result
            if(result instanceof Map){
                ((Map) result).put("t", System.currentTimeMillis());
            }
        } catch (Throwable e) {
            //异常通知
            System.out.println("this method "+ methodName+" end.ex message<"+e+">");
            throw new RuntimeException(e);
        }
        //后置通知
        System.out.println("The method "+ methodName+" end.");
        return result;
    }

}
